package com.uml.umlwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uml.umlwork.dto.course.AddCourseDTO;
import com.uml.umlwork.dto.course.UpdateCourseDTO;
import com.uml.umlwork.entity.Class;
import com.uml.umlwork.entity.Course;
import com.uml.umlwork.mapper.ClassMapper;
import com.uml.umlwork.mapper.CourseMapper;
import com.uml.umlwork.service.CourseService;
import com.uml.umlwork.vo.course.select.CourseSelectVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author Zhu
 * @date 2020/12/25
 */
@Service
public class CourseServiceImpl implements CourseService {

    private final CourseMapper courseMapper;
    private final ClassMapper classMapper;

    public CourseServiceImpl(CourseMapper courseMapper, ClassMapper classMapper) {
        this.courseMapper = courseMapper;
        this.classMapper = classMapper;
    }


    @Override
    public List<Course> getAllOpenCourse(String year, String season, String isOpen) {
        return courseMapper.getAllOpenCourse(year, season, isOpen);
    }

    @Override
    public void closeCourseByCourseId(Integer courseId, Integer open) {
        Course course = getCourseById(courseId);
        course.setIsOpen(open.equals(1));
        courseMapper.updateById(course);
    }

    @Override
    public void createNewCourse(AddCourseDTO dto) {
        Course course = new Course();
        course.setCourseName(dto.getCourseName())
                .setSeason(dto.getSeason())
                .setYear(dto.getYear())
                .setIsOpen(false);
        courseMapper.insert(course);
    }

    @Override
    public void deleteCourse(Integer courseId) {
        Assert.isTrue(classMapper.selectList(new QueryWrapper<Class>().eq("course_id", courseId)).size() == 0,
                "已开班的课程不能删除,只能关闭");
        courseMapper.deleteById(courseId);
    }

    @Override
    public void updateCourse(UpdateCourseDTO dto) {
        Course course = getCourseById(dto.getCourseId());
        Assert.isFalse(course.getIsOpen(),"已开班的课程不能修改, 请先将其关闭");
        course.setYear(dto.getYear())
                .setSeason(dto.getSeason()).setCourseName(dto.getCourseName());
        courseMapper.updateById(course);
    }

    private Course getCourseById(Integer id) {
        return Optional.ofNullable(courseMapper.selectById(id))
                .orElseThrow(() -> new RuntimeException("该id:" + id + "有误"));
    }
}
